// 滤波、功率谱计算
var ref = require("ref-napi");
var ffi = require("ffi-napi");
var ArrayType = require("ref-array-napi");
import { join } from "path";
const Int = ref.types.int;
const Bool = ref.types.bool;
const Double = ref.types.double;
const DoubleArray = ArrayType(Double);
const IntArray = ArrayType(Int);
const config = JSON.parse(process.argv[4]);
const _product_path = process.argv[3];
const channel = 2;
const step = 10;

let signalProcess = ffi.Library(
  join(_product_path, "/dll/signal_process.dll"),
  {
    clear_fft_cache: ["void", []],
    fft_ps: [Bool, [Int, Double, Double, Int, Int, DoubleArray, DoubleArray]],
  }
);

let hrvProcess = ffi.Library(join(_product_path, "/dll/HRV_process.dll"), {
      //计算心率前的初始化
      init_heart_rate: ["void", []],
  hrv_spec: [
    "void",
    [
      DoubleArray,
      Int,
      Int,
      DoubleArray,
      DoubleArray,
      IntArray,
      DoubleArray,
      DoubleArray,
      DoubleArray,
      DoubleArray,
      DoubleArray,
      DoubleArray,
      DoubleArray,
    ],
  ],
});

// 接收消息
process.on("message", async function ({ type, data }) {
  if (type === "calculate-fft-ps-halfway") {
    let ps_s: any = [
      new DoubleArray(config.hrv.fftWindow / 2 + 1),
      new DoubleArray(config.hrv.fftWindow / 2 + 1),
    ]; //频谱数组，长度为window/2+1，存储每个频率能量，单位为dB
    let psd_s = [
      new DoubleArray(config.hrv.fftWindow / 2 + 1),
      new DoubleArray(config.hrv.fftWindow / 2 + 1),
    ]; //频谱密度数组，长度为window/2+1，存储每个频率能量，能量单位为dB
    signalProcess.clear_fft_cache();
    console.log("memoryUsage1", process.memoryUsage());
    for (let i = 0; i < config.hrv.fftWindow; i++) {
      for (
        let current_channel = 0;
        current_channel < channel;
        current_channel++
      ) {
        signalProcess.fft_ps(
          current_channel,
          config.eegFilter.sample_rate,
          data[current_channel][i] || 0,
          step,
          config.hrv.fftWindow,
          ps_s[current_channel],
          psd_s[current_channel]
        );
      }
    }
    console.log("memoryUsage2", process.memoryUsage());
    signalProcess.clear_fft_cache();
    ps_s = null;
    process.send!({
      type: "calculate-fft-ps-result",
      data: psd_s,
    });
  }
  if (type === "calculate-hrv-halfway") {
    hrvProcess.init_heart_rate();
    let hr_time = new DoubleArray(2000); //用于存放心率横坐标（时间轴）的数组
    let hr = new DoubleArray(2000); //用于存放心率纵坐标（心率）的数组；
    console.log("memoryUsage3", process.memoryUsage());

    let number_of_hr = new IntArray([0]);
    let timedomain_NNI = new DoubleArray(10); //1、NNI 参数、平均RR间隔时间(NNI_Average)、RR间隔最小值(NNI_Min)、RR间隔最大值(NNI_Max)、SDNN、RMSSD、NN20、NN50、pNN20、pNN50
    let timedomain_NNI_diff = new DoubleArray(4); //2、NNI差值参数：相邻RR间隔平均值、相邻RR间隔最小值、相邻RR间隔最大值、相邻RR间隔标准差
    let timedomain_HR = new DoubleArray(4); //3、HR参数：HR平均值、HR最小值、HR最大值、HR标准差
    let hrv_fdomain_spec = new DoubleArray(6); //绝对ULF、VLF、LF、HF，TP、LF/HF，
    let hrv_fdomain_percent = new DoubleArray(4); //相对功率：ULF、VLF、LF、HF
    let hrv_fdomain_spec_db = new DoubleArray(5); //对数功率：ULF、VLF、LF、HF、TP
    let hrv_fdomain_max_f = new DoubleArray(5); //功率最大频率点：ULF、VLF、LF、HF
    console.log('data.length',data.length);
    console.log('config.irFilter.ir_sample_rate',config.irFilter.ir_sample_rate);
    hrvProcess.hrv_spec(
      data,
      data.length,
      config.irFilter.ir_sample_rate,
      hr_time,
      hr,
      number_of_hr,
      timedomain_NNI,
      timedomain_NNI_diff,
      timedomain_HR,
      hrv_fdomain_spec,
      hrv_fdomain_percent,
      hrv_fdomain_spec_db,
      hrv_fdomain_max_f
    );
    console.log('1');
    
    process.send!({
      type: "calculate-hrv-result",
      data: {
        hr_time,
        hr,
        number_of_hr,
        timedomain_NNI,
        timedomain_NNI_diff,
        timedomain_HR,
        hrv_fdomain_spec,
        hrv_fdomain_percent,
        hrv_fdomain_spec_db,
        hrv_fdomain_max_f,
      },
    });
  }
});
